// Copyright 2008 web2me.dev
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package net.web2me.parsers;

import java.io.File;

import net.web2me.api.util.FileUtil;
import net.web2me.api.util.UtilityException;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Handles the comments on a image
 * @author web2me
 *
 */
public class CommentsHandler implements Runnable {
	
	private Integer commentsCount = 0;
	
	private Document document;
	
	private String dir;
	
	private Logger logger = Logger.getLogger(CommentsHandler.class);
	
	public CommentsHandler(Document document, String dir){
		this.document = document;
		this.dir = dir;
	}

	public void run(){
		logger.info("Parsing image comments");
		
		NodeList bolds = document.getElementsByTagName("b");
		Element bold;
		Element userLink;
		String userName = "";
		
		for(int i = 0; i < bolds.getLength(); i++){
			bold = (Element) bolds.item(i);
			
			// Looks for text nodes, since getTextContent() is not implemented yet
			NodeList boldChilds = bold.getChildNodes();
			Node child;
			
			for(int j = 0; j < boldChilds.getLength(); j++){
				child = boldChilds.item(j);
				
				if(child.getNodeType() == Element.TEXT_NODE){
					logger.info("A TEXT_NODE has been found");
					
					if(child.getNodeValue().indexOf("Posted by") > -1){
						// Comment found
						logger.info("A comment has been found");
						commentsCount++;
						
						userLink = (Element) bold.getElementsByTagName("a").item(0);
						userName = userLink.getTextContent();
						
						try {
							FileUtil.setContents(new File(dir + "/" + getImageId() + ".comments"), 
									userName + " (" + getPostedDate(bold) + "): " + getComment() + "\n"
								);
						} catch (UtilityException e) {
							throw new RuntimeException("An error occured saving the image comments", e);
						}
					}else{
						logger.info("VALUE:" + child.getNodeValue());
					}
					
				}
			}
		}
		
		logger.info(commentsCount == 0 ? "No comments found": commentsCount + " comment/s found");
	}
	
	private String getComment(){
		return "This is not implemented yet";
	}
	
	private String getPostedDate(Element bold){
		int init = bold.getTextContent().indexOf("Date posted: ");
		
		return bold.getTextContent().substring(init);
	}
	
	private String getImageId(){
		NodeList inputs = document.getElementsByTagName("input");
		Element input;
		
		for(int i = 0; i < inputs.getLength(); i++){
			input = (Element) inputs.item(i);
			
			if("vid".equals(input.getAttribute("name"))){
				return input.getAttribute("value");
			}
		}
		
		return "no-image-id-found";
	}
	
}
